<template>
    <QuillEditor
        ref="myQuillEditor"
        class="quill-editor"
        theme="snow"
        contentType="html"
        v-model:content="editorContent"
        :options="data.editorOption"
        @update:content="handleUpdate()"
    >
    </QuillEditor>
    <!-- 使用自定义图片上传 -->
    <input type="file" hidden accept=".jpg,.png,.jpeg" ref="fileBtn" @change="handleUpload" />
  </template>
  
  <script setup> 
  import { Quill, QuillEditor } from '@vueup/vue-quill';
  import '@vueup/vue-quill/dist/vue-quill.snow.css'; //snow主题使用次样式
  import { computed, getCurrentInstance, reactive,ref, watch, toRaw, onMounted, onUpdated } from 'vue';
  // import BlotFormatter from "quill-blot-formatter"
  // Quill.register("modules/blotFormatter", BlotFormatter)
  import axios from 'axios'
  import { localGet } from '@/utils'

  // const modules = {
  //   module: BlotFormatter,
  // }
  const fileBtn = ref()
  const myQuillEditor = ref(null)
  const props = defineProps({
    height: {
      type: Number,
      default: 500
    },
    content: {
      type: String,
      default: ''
    },   
  });
  const data = reactive({
    content: '',
    editorOption:{
      modules:{
        toolbar: [
        ['image'],
        ]
      },
      placeholder: '请输入内容...'
    }
  })
const editorContent = computed({
  get: () => props.content,
  set: (val) => {
    emit('update:content', val);    
  }
})
const emit = defineEmits(['update:content', 'updateValue']);
  // const emit = defineEmits(['updateValue']);
  const { proxy } = getCurrentInstance();
  
  //监听图片按钮点击后，点击上传
  const imgHandler = (state) => {
    if (state) {
      fileBtn.value.click()
    }
  }
  // 处理图片上传  
const handleUpload = (e) => {
  const files = Array.prototype.slice.call(e.target.files)
  if (!files) {
    return
  }
  const formdata = new FormData()
  formdata.append('images', files[0])
  axios.post('/uploadImage/',formdata, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'token': localGet('token'),
      },
    }).then(res =>{
    if (res.code == 200){
      const quill = toRaw(myQuillEditor.value).getQuill()
      const length = quill.getSelection().index
      quill.insertEmbed(length, 'image', res.data.results)
      quill.setSelection(5, 10)
    }else{
      ElMessage.error("很遗憾，图片上传失败！")      
    }
  })
}
// 更新内容,发还给父组件
const handleUpdate = () => {
  let quill = myQuillEditor.value.getQuill()
  console.log('quill', quill)

  // const range = quill.getSelection();
  // const { index, length } = quill.getSelection();
  // console.log('range', range)
  // console.log('handleUpdate length', length)
  // console.log('handleUpdate index', index)
  // quill.setSelection(index, length)
  const text=toRaw(myQuillEditor.value).getHTML()
  emit('updateValue', text)
}
onMounted(() => {
  // console.log('props.content', props.content)
  toRaw(myQuillEditor.value).setHTML(props.content)
  const quill = toRaw(myQuillEditor.value).getQuill()
  if (myQuillEditor.value) {
    quill.getModule('toolbar').addHandler('image', imgHandler)
  }
})
// 页面更新后，更新本子组件的内容
onUpdated(() => {
  console.log('props.content:', props.content)
  toRaw(myQuillEditor.value).setHTML(props.content)

  // const text=toRaw(myQuillEditor.value).getHTML()
  // let quill = myQuillEditor.value.getQuill()
  // console.log('quill实例：', quill)
  // console.log('onupdated text.length', text.length)
  // quill.setSelection(text.length)
})
</script>  
<style>
.quill-editor {
  margin: 1px;
}
</style>